<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 实名认证
 * @ author: zuorenci
 * @ email: 904725327@qq.com
 * @ date: 2017/10/24 21:01
 */
class Autonym extends Model
{
    public $timestamps = false;

    protected $table = 'autonym';

    protected $primaryKey = 'autonymID';

    protected $fillable = [
        'autonymID', //主键id
        'userID', //用户id
        'phone', //手机号
        'name', //用户真实姓名
        'indentity_card', //身份证号
        'hand_card', //手持身份证照
        'front_card', //正面照片
        'back_card', //背面照片
        'time', //上传时间
        'status', //审核状态 1为未认证，2为认证中，3认证未通过，4为已认证
        'note', //审核备注
        'id', //审核人id
        'audit_time', //时间
        'hand_card_oss',
        'front_card_oss',
        'back_card_oss',
    ];

    protected $casts = ['hand_card', 'front_card', 'back_card'];

    public function getHandCardAttribute($value)
    {
        return \App\Library\HandleFile::handleFilePath($value, $this->hand_card_oss);
    }

    public function getFrontCardAttribute($value)
    {
        return \App\Library\HandleFile::handleFilePath($value, $this->front_card_oss);
    }

    public function getBackCardAttribute($value)
    {
        return \App\Library\HandleFile::handleFilePath($value, $this->back_card_oss);
    }

    //关联用户表
    public function user()
    {
        return $this->hasOne('App\\Models\\User', 'userID', 'userID');
    }
    /**
     * @author zuorenci
     * @describe 判断身份证号是否唯一
     * @access public
     * @date   2017/11/3
     * @param string $identity_card 身份证号
     * @param int $type 用户身份1代理，2商家，3vip会员，4普通会员
     * @param int $is_first 是否为第一次提交 1为第一次2为非第二次
     * @param int $user_id 用户id
     * @return mixed
     */
    public function checkIdentityCard($identity_card, $type, $is_first = 1, $user_id = 0)
    {
        if (empty($identity_card) || empty($type)) {
            return ['status' => 0, 'msg' => '参数缺失'];
        }
        if ($is_first != 1) {
            if (!in_array($is_first, [1, 2]) || empty($user_id)) {
                return ['status' => 0, 'msg' => '参数缺失'];
            }
        }
        $where1 = array();
        if ($type == 2) {
            //商家
            $where1['type'] = 2;
        } else {
            //其他身份
            $where1['type'] = ['in', [1, 3, 4]];
        }
        $where['indentity_card'] = $identity_card;
        if ($is_first != 1) {
            $where1['userID'] = ['neq', $user_id];
        }
        //$num = $this->with('user')->where($where)->count();
        $num = $this->with('user')
            ->whereHas(
                'user', function ($query) use ($where1) {
                    $query->where($where1);
                })
            ->where($where)
            ->count();
        if ($num >= 1) {
            return ['status' => 0, 'msg' => '该身份证号已注册'];
        } else {
            return ['status' => 1, 'msg' => '满足唯一'];
        }
    }
}
